import { getUserDetail, getUserInfo, login } from '@/api/user'
import { getToken, setToken, removeToken, setTime } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  updatePhoto(state, photo) {
    state.userInfo.staffPhoto = photo
    console.log('1111')
  },
  // vuex保存token
  setToken(state, token) {
    // 存储到vuex
    state.token = token
    // 存储到Cookie
    setToken(token)
    // 存储当时的时间戳
    setTime(Date.now())
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login({ commit }, payload) {
    const data = await login(payload)
    commit('setToken', data)
  },
  async getUserInfo({ commit }) {
    const data = await getUserInfo()
    const data2 = await getUserDetail(data.userId)
    commit('setUserInfo', {
      ...data,
      ...data2
    })
  },
  // 退出登录
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
    // 3. 重置路由(每个人登进来权限是不一样的, 需要在退出时重置成默认的)
    resetRouter()
    // 左侧菜单数据也重置
    // 默认模块会在当前命名中间查找。
    // root: true代表mutations从根命名空间中查看
    // 4. 将vuex中路由信息数组, 也重置
    // 需求: 需要调用 permission 模块中的 setRoutes (mutation)
    commit('permission/setRoutes', [], { root: true })
    // 5. 清除主题色信息
    commit('settings/resetTheme', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
